package tcards.android;

import util.StringUtil;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class NumberField extends RelativeLayout {
	private TextView mLabel;
	private EditText mInput;
	
	private void init(AttributeSet attrs) {
		TypedArray tArray = getContext().obtainStyledAttributes(attrs, R.styleable.Field);
		mLabel =  (TextView) findViewById(R.id.numberLabel);
		mInput =  (EditText) findViewById(R.id.numberInput);
		
		String text = tArray.getString(R.styleable.Field_label);
        if (text != null) { 
        	getLabel().setText(text + ":");
        }
		
        getInput().getLayoutParams().width = tArray.getInt(R.styleable.Field_inputSize, 350);
        
		tArray.recycle();
	}	
	
	public NumberField(Context context) {
		this(context, null, 0);
	}

	public NumberField(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public NumberField(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		LayoutInflater li = LayoutInflater.from(context);
		addView(li.inflate(R.layout.number_field, this, false));
		if (attrs != null) {
			init(attrs);
		}
		getInput().setHorizontallyScrolling(true);
	}

	public TextView getLabel() {
		return mLabel;
	}
	
	public EditText getInput() {
		return mInput;
	}
	
	public boolean isValid() {
		try {
			Integer.parseInt(mInput.getText().toString());
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}
	
	public int getNumberValue() {
		String value = mInput.getText().toString();
		if (StringUtil.IsNullOrEmpty(value)) {
			return 0;
		}
		return Integer.parseInt(value);
	}

	public void setNumberValue(int personnelCount) {
		mInput.setText(Integer.toString(personnelCount));
	}
}